package com.yang.listeners;

import com.yang.YangGrade;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

public class Listeners implements Listener {

    private YangGrade yangGrade;

    public Listeners(YangGrade yangGrade) {
        this.yangGrade = yangGrade;
    }

    // 打开品质调整箱 菜单点击
    @EventHandler
    public void onInventoryClick(InventoryClickEvent event) {
        //判断打开的菜单是不是品质调整箱
        if (event.getView().getTitle().equals("品质调整箱")) {
            // 如果点击或者拖动物品 除了1到8不可以动 其他的都可以随便拖放
            if (event.getRawSlot() >= 1 && event.getRawSlot() <= 8) {
                event.setCancelled(true);
            }
            //判断玩家点了哪个
            Player player = (Player) event.getWhoClicked();
            ItemStack currentItem = event.getCurrentItem();
            if (currentItem != null && currentItem.getType() != null) {
                //判断玩家是不是点击的铁砧
                if (currentItem.getType() == Material.ANVIL) {
                    //捕获异常
                    try {
                        ItemStack item = event.getInventory().getItem(0);
                        player.sendMessage(item.getType().toString());
                        // 执行品质调整代码
                        updateQuality(item);
                    }catch (Exception e){
                        this.yangGrade.getLogger().info(ChatColor.RED + "这个BUG不用管");
                        player.sendMessage("请放入物品");
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void updateQuality(ItemStack item) {
        // 获取物品的lore
        List<String> lore = item.getItemMeta().getLore();
        // 判断lore有没有信息为 品级
        if(lore.contains("品级")){
            // 获取品级的下标
            int index = lore.indexOf("品级");
            // 如果有品级 并重新设置品级信息为 1
            if(index != -1){
                lore.set(index, "品级:1");
                // 设置lore
                this.yangGrade.getLogger().info("品级已更新");
            }
        }
    }

    //监听玩家手中物品
    @EventHandler
    public void onPlayerItem(PlayerInteractEvent e) {
        // 监听主手的物品类型
        Player player = e.getPlayer();
        ItemStack item = player.getInventory().getItemInMainHand();
        player.sendMessage(item.getType().toString());
    }

}
